<template>
  <div class="page-container">
    <div class="page-header">
      <h2 class="page-title">教师审批管理</h2>
      <el-tag v-if="adminInfo.level" type="info" class="admin-tag">{{ adminInfo.label }}</el-tag>
    </div>

    <el-tabs v-model="activeTab" type="card">
      <el-tab-pane label="待审批申请" name="pending">
        <el-card>
          <el-table :data="pendingApprovals" border style="width: 100%" v-loading="loading">
            <el-table-column prop="usercode" label="教师工号" width="120" />
            <el-table-column prop="fullName" label="姓名" width="100" />
            <el-table-column prop="email" label="邮箱" width="180" />
            <el-table-column label="申请权限" width="120">
              <template #default="{ row }">
                <el-tag :type="getRoleTagType(row.requestedRole)">
                  {{ getRoleLabel(row.requestedRole) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="orgName" label="所属部门" width="150" />
            <el-table-column prop="requestTime" label="申请时间" width="180">
              <template #default="{ row }">
                {{ formatDate(row.requestTime) }}
              </template>
            </el-table-column>
            <el-table-column label="操作" width="200" fixed="right">
              <template #default="{ row }">
                <el-button
                  v-if="canApprove(row)"
                  type="success"
                  link
                  @click="handleApprove(row, true)"
                >
                  通过
                </el-button>
                <el-button
                  v-if="canApprove(row)"
                  type="danger"
                  link
                  @click="handleApprove(row, false)"
                >
                  拒绝
                </el-button>
                <el-button
                  type="primary"
                  link
                  @click="viewDetails(row)"
                >
                  详情
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-tab-pane>
      <el-tab-pane label="已处理申请" name="processed">
        <el-card>
          <el-table :data="processedApprovals" border style="width: 100%" v-loading="loading">
            <el-table-column prop="usercode" label="教师工号" width="120" />
            <el-table-column prop="fullName" label="姓名" width="100" />
            <el-table-column label="申请权限" width="120">
              <template #default="{ row }">
                <el-tag :type="getRoleTagType(row.requestedRole)">
                  {{ getRoleLabel(row.requestedRole) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="审批状态" width="100">
              <template #default="{ row }">
                <el-tag :type="row.approvalStatus === 'APPROVED' ? 'success' : 'danger'">
                  {{ row.approvalStatus === 'APPROVED' ? '已通过' : '已拒绝' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="approverName" label="审批人" width="100" />
            <el-table-column prop="approvalTime" label="审批时间" width="180">
              <template #default="{ row }">
                {{ formatDate(row.approvalTime) }}
              </template>
            </el-table-column>
            <el-table-column prop="approvalComment" label="审批意见" width="200" />
            <el-table-column label="操作" width="100" fixed="right">
              <template #default="{ row }">
                <el-button
                  type="primary"
                  link
                  @click="viewDetails(row)"
                >
                  详情
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-tab-pane>
    </el-tabs>

    <!-- 审批对话框 -->
    <el-dialog
      v-model="approvalDialogVisible"
      :title="isApprove ? '通过申请' : '拒绝申请'"
      width="500px"
    >
      <el-form ref="approvalFormRef" :model="approvalForm" label-width="100px">
        <el-form-item label="教师姓名">
          <el-input v-model="approvalForm.fullName" disabled />
        </el-form-item>
        <el-form-item label="申请权限">
          <el-input v-model="approvalForm.roleLabel" disabled />
        </el-form-item>
        <el-form-item label="审批意见" prop="comment">
          <el-input
            v-model="approvalForm.comment"
            type="textarea"
            :rows="3"
            :placeholder="isApprove ? '请输入通过意见' : '请输入拒绝原因'"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="approvalDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitApproval">确定</el-button>
      </template>
    </el-dialog>

    <!-- 详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="申请详情"
      width="600px"
    >
      <el-descriptions :column="1" border>
        <el-descriptions-item label="教师工号">{{ currentDetail.usercode }}</el-descriptions-item>
        <el-descriptions-item label="教师姓名">{{ currentDetail.fullName }}</el-descriptions-item>
        <el-descriptions-item label="邮箱">{{ currentDetail.email }}</el-descriptions-item>
        <el-descriptions-item label="申请权限">
          <el-tag :type="getRoleTagType(currentDetail.requestedRole)">
            {{ getRoleLabel(currentDetail.requestedRole) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="所属部门">{{ currentDetail.orgName }}</el-descriptions-item>
        <el-descriptions-item label="申请时间">{{ formatDate(currentDetail.requestTime) }}</el-descriptions-item>
        <el-descriptions-item label="审批状态">
          <el-tag v-if="currentDetail.approvalStatus === 'PENDING'" type="warning">待审批</el-tag>
          <el-tag v-else-if="currentDetail.approvalStatus === 'APPROVED'" type="success">已通过</el-tag>
          <el-tag v-else-if="currentDetail.approvalStatus === 'REJECTED'" type="danger">已拒绝</el-tag>
        </el-descriptions-item>
        <el-descriptions-item v-if="currentDetail.approvalStatus !== 'PENDING'" label="审批人">
          {{ currentDetail.approverName }}
        </el-descriptions-item>
        <el-descriptions-item v-if="currentDetail.approvalStatus !== 'PENDING'" label="审批时间">
          {{ formatDate(currentDetail.approvalTime) }}
        </el-descriptions-item>
        <el-descriptions-item v-if="currentDetail.approvalStatus !== 'PENDING'" label="审批意见">
          {{ currentDetail.approvalComment }}
        </el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <el-button @click="detailDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useUserStore } from '../../stores/user'
import request from '../../utils/request'
import { ElMessage } from 'element-plus'

const userStore = useUserStore()

// 管理员信息
const adminInfo = computed(() => {
  let level = '';
  let label = '普通教师';
  let orgId = null;
  
  if (userStore.userInfo?.userType?.toLowerCase() === 'super_admin') {
    level = 'SUPER_ADMIN';
    label = '超级管理员';
    return { level, label, orgId };
  }
  
  if (!userStore.userInfo?.extraInfo) {
    return { level, label, orgId };
  }
  
  try {
    const extraInfo = JSON.parse(userStore.userInfo.extraInfo);
    level = extraInfo.admin_role || '';
    orgId = userStore.userInfo.orgId;
    
    switch (level) {
      case 'SCHOOL_ADMIN':
        label = '校级管理员';
        break;
      case 'DEPARTMENT_ADMIN':
        label = '院级管理员';
        break;
      case 'MAJOR_ADMIN':
        label = '系级管理员';
        break;
      case 'CLASS_ADMIN':
        label = '班级管理员';
        break;
    }
  } catch (e) {
    console.error('解析管理员信息失败', e);
  }
  
  return { level, label, orgId };
});

// 获取角色权限级别
const getRoleLevel = (role) => {
  switch (role) {
    case 'SUPER_ADMIN': return 5;
    case 'SCHOOL_ADMIN': return 4;
    case 'DEPARTMENT_ADMIN': return 3;
    case 'MAJOR_ADMIN': return 2;
    case 'CLASS_ADMIN': return 1;
    case 'TEACHER': return 0;
    default: return -1;
  }
};

// 判断当前用户是否可以审批指定申请
const canApprove = (approval) => {
  // 超级管理员可以审批所有申请
  if (adminInfo.value.level === 'SUPER_ADMIN') {
    return true;
  }
  
  // 获取当前管理员级别
  const adminLevel = getRoleLevel(adminInfo.value.level);
  
  // 根据规则判断是否可以审批
  // 普通教师和班级管理员需要系级以上管理员审批
  if ((approval.requestedRole === 'TEACHER' || approval.requestedRole === 'CLASS_ADMIN') && adminLevel >= 2) {
    return true;
  }
  
  // 系级管理员需要院级以上管理员审批
  if (approval.requestedRole === 'MAJOR_ADMIN' && adminLevel >= 3) {
    return true;
  }
  
  // 院级管理员需要校级以上管理员审批
  if (approval.requestedRole === 'DEPARTMENT_ADMIN' && adminLevel >= 4) {
    return true;
  }
  
  // 校级管理员需要超级管理员审批
  if (approval.requestedRole === 'SCHOOL_ADMIN' && adminLevel >= 5) {
    return true;
  }
  
  return false;
};

// 获取角色标签类型
const getRoleTagType = (role) => {
  switch (role) {
    case 'SCHOOL_ADMIN': return 'danger';
    case 'DEPARTMENT_ADMIN': return 'warning';
    case 'MAJOR_ADMIN': return 'success';
    case 'CLASS_ADMIN': return 'info';
    case 'TEACHER': return '';
    default: return '';
  }
};

// 获取角色显示标签
const getRoleLabel = (role) => {
  switch (role) {
    case 'SCHOOL_ADMIN': return '校级管理员';
    case 'DEPARTMENT_ADMIN': return '院级管理员';
    case 'MAJOR_ADMIN': return '系级管理员';
    case 'CLASS_ADMIN': return '班级管理员';
    case 'TEACHER': return '普通教师';
    default: return '未知';
  }
};

// 格式化日期
const formatDate = (dateStr) => {
  if (!dateStr) return '';
  const date = new Date(dateStr);
  return date.toLocaleString();
};

const activeTab = ref('pending');
const loading = ref(false);
const pendingApprovals = ref([]);
const processedApprovals = ref([]);

// 审批对话框相关
const approvalDialogVisible = ref(false);
const approvalFormRef = ref(null);
const approvalForm = ref({
  approvalId: null,
  fullName: '',
  roleLabel: '',
  comment: '',
});
const isApprove = ref(true);

// 详情对话框相关
const detailDialogVisible = ref(false);
const currentDetail = ref({});

// 加载待审批申请
const loadPendingApprovals = async () => {
  loading.value = true;
  try {
    const response = await request.get('/teacher-approvals/status/PENDING');
    pendingApprovals.value = response.data || [];
  } catch (error) {
    console.error('获取待审批申请失败:', error);
    ElMessage.error('获取待审批申请失败');
  } finally {
    loading.value = false;
  }
};

// 加载已处理申请
const loadProcessedApprovals = async () => {
  loading.value = true;
  try {
    // 获取已通过和已拒绝的申请
    const approvedResponse = await request.get('/teacher-approvals/status/APPROVED');
    const rejectedResponse = await request.get('/teacher-approvals/status/REJECTED');
    
    const approved = approvedResponse.data || [];
    const rejected = rejectedResponse.data || [];
    
    // 合并并按审批时间降序排序
    processedApprovals.value = [...approved, ...rejected].sort((a, b) => {
      return new Date(b.approvalTime) - new Date(a.approvalTime);
    });
  } catch (error) {
    console.error('获取已处理申请失败:', error);
    ElMessage.error('获取已处理申请失败');
  } finally {
    loading.value = false;
  }
};

// 处理审批
const handleApprove = (row, approve) => {
  isApprove.value = approve;
  approvalForm.value = {
    approvalId: row.approvalId,
    fullName: row.fullName,
    roleLabel: getRoleLabel(row.requestedRole),
    comment: '',
  };
  approvalDialogVisible.value = true;
};

// 提交审批
const submitApproval = async () => {
  if (!approvalForm.value.comment) {
    ElMessage.warning('请输入审批意见');
    return;
  }
  
  try {
    await request.post(`/teacher-approvals/${approvalForm.value.approvalId}/approve`, {
      approverId: userStore.userInfo.userId,
      isApproved: isApprove.value,
      comment: approvalForm.value.comment
    });
    
    ElMessage.success('审批成功');
    approvalDialogVisible.value = false;
    
    // 重新加载数据
    loadPendingApprovals();
    loadProcessedApprovals();
  } catch (error) {
    console.error('审批失败:', error);
    ElMessage.error('审批失败: ' + (error.response?.message || error.message));
  }
};

// 查看详情
const viewDetails = (row) => {
  currentDetail.value = row;
  detailDialogVisible.value = true;
};

// 组件挂载时加载数据
onMounted(() => {
  loadPendingApprovals();
  loadProcessedApprovals();
});
</script>

<style scoped>
.page-container {
  padding: 20px;
}

.page-header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.page-title {
  margin: 0;
  margin-right: 15px;
}

.admin-tag {
  margin-right: auto;
}
</style> 